package com.uziot.bucket.advice.response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 功能描述: <br>
 * <>
 * controller出现异常时响应JSON串
 *
 * @author shidt
 * @date 2020-03-09 0:45
 */
@ControllerAdvice
@SuppressWarnings("ALL")
public class CommonExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(CommonExceptionHandler.class);

    /**
     * catch所有controller异常，响应json
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public DefaultResponse handleException(Exception e) {
        log.error("controller advice,", e);
        return DefaultResponse.builder()
                .glue(ResponseCode.UNKNOWN)
                .data(e.getCause().toString())
                .build();
    }


    /**
     * valid注解校验异常
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public DefaultResponse handleValidException(BindException e) {
        log.error("controller advice,", e);
        String names = "";
        for (FieldError fieldError : e.getFieldErrors()) {
            if (!StringUtils.isEmpty(names)) {
                names += ", ";
            }
            names += fieldError.getField();
        }
        return DefaultResponse.builder()
                .code(ResponseCode.UNKNOWN.getCode())
                .msg("参数错误")
                .data(names)
                .build();
    }

}
